package com.qf.com.qf.details.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.com.qf.details.mapper.GrassCommentMapper;
import com.qf.com.qf.details.service.GrassCommentService;
import com.qf.com.qf.details.vo.GrassDetailsVO;
import com.qf.com.qf.grass.service.GrassService;
import com.qf.common.core.common.PageVO;
import com.qf.common.core.entity.Grass;
import com.qf.common.core.entity.GrassComment;
import com.qf.common.core.entity.User;
import com.qf.common.core.exception.CustomerException;
import com.qf.common.core.utils.UserUtils;
import com.qf.user.service.UserService;
import org.jacoco.agent.rt.internal_3570298.core.internal.flow.IFrame;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zdl
 * @date 2025/3/28
 */
@Service
public class GrassCommentServiceImpl implements GrassCommentService {

    @Resource
    private GrassCommentMapper grassCommentMapper;
    @Resource
    private GrassService grassService;

    @Resource
    private UserService userService;


    @Override
    public GrassDetailsVO details(Integer grassId) {

        Grass grass = grassService.getGrassById(grassId);
        User userById = userService.getUserById(grass.getUid());
        GrassDetailsVO vo = new GrassDetailsVO();
        String imgPath = grass.getImgPath();
        List<String> split = Arrays.asList(imgPath.split(","));
        vo.setImgUrl(split);
        vo.setUsername(userById.getUsername());

        // 分页查询一级评论
        Page<GrassComment> page = new Page<>(1, 10);
        // select * from grass_comment where grass_id = grassId and parent_id is null
        Page<GrassComment> commentPage = grassCommentMapper.selectPage(page, new LambdaQueryWrapper<GrassComment>()
                .eq(GrassComment::getGrassId, grassId)
                .isNull(GrassComment::getParentId));

//        PageVO<GrassComment> pageVO = new PageVO<>();
//        pageVO.setTotal(commentPage.getTotal());
//        pageVO.setDataList(commentPage.getRecords());
        vo.setCommentPage(commentPage);
        // 查询二级评论
        if (!commentPage.getRecords().isEmpty()) {
            // 查询根节点 id
            List<Integer> rootIds = commentPage.getRecords().stream()
                    .map(GrassComment::getId)
                    .collect(Collectors.toList());
            // select * from grass_comment where parent_id in (rootIds) and grass_id = grassId
            List<GrassComment> grassComments = grassCommentMapper.selectList(new LambdaQueryWrapper<GrassComment>()
                    .in(GrassComment::getParentId, rootIds)
                    .eq(GrassComment::getGrassId, grassId));
            // 二级评论按根节点分组
            Map<Integer, List<GrassComment>> repliesMap  = grassComments.stream().collect(Collectors.groupingBy(GrassComment::getRootId));
            // 给一级评论设置二级评论
            commentPage.getRecords().forEach(comment -> {
                //getOrDefault 防止二级评论不存在
                comment.setReplies(repliesMap.getOrDefault(comment.getId(), Collections.emptyList()));
            });
        }
        BeanUtils.copyProperties(grass, vo);
        return vo;
    }


    @Override
    public Integer addComment(GrassComment grassComment) {
        if (grassComment.getContent() == null || grassComment.getContent().trim().equals("")) {
            throw new CustomerException("4003", "评论内容不能为空");
        }
        grassComment.setUid(UserUtils.getUser());
        if (grassComment.getParentId() != null) {
            // 二级评论验证父评论是否存在 select * from grass_comment where id = parentId and grass_id = grassId
            GrassComment parent = grassCommentMapper.selectById(grassComment.getParentId());
            if (parent == null) {
                throw new CustomerException("4003", "父评论不存在");
            }
            // 设置根节点 rootId
            grassComment.setRootId(parent.getRootId());
            // 设置根节点 rootId
            grassComment.setRootId(parent.getRootId() != null ? parent.getRootId() : parent.getId());
        }
        grassCommentMapper.insert(grassComment);
        return grassComment.getId();
    }
}
